package com.mtl.inmigrant.shoes.adapter;

import java.util.List;

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;

import com.mtl.inmigrant.shoes.R;
import com.mtl.inmigrant.shoes.entity.ShoeActionsInmigrant;
import com.mtl.inmigrant.shoes.entity.TypeActivityShoes.typeActionShoe;
import com.mtl.inmigrant.shoes.sqlite.MyConnectionSQLiteHelper;
import com.mtl.inmigrant.shoes.sqlite.ShoesDataSource;

public class ImmigrantListAdapter extends ArrayAdapter<ShoeActionsInmigrant> {
	protected final Activity context;
	private LayoutInflater inflator;
	private ShoesDataSource dataSource;
	
	public ImmigrantListAdapter(Activity context,
			List<ShoeActionsInmigrant> list, ShoesDataSource dataSource) {
		super(context, R.layout.activities_list, list);
		inflator = context.getLayoutInflater();
		this.context = context;
		this.dataSource = dataSource;
	}

	static class ViewHolder {
		protected TextView text;
		protected CheckBox checkbox;
		protected String idElement;
		
		public String toString(){
			return text.getText().toString();	
		}
		
		public String getIdElement(){
			return idElement;
		}
		
		public void setIdElement(String id){
			this.idElement = id;
		}
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder viewHolder;
		ShoeActionsInmigrant shoeActionInmigrant = (ShoeActionsInmigrant) this.getItem( position );   
		if (convertView == null) {

			convertView = inflator.inflate(R.layout.activities_list, parent, false);
			viewHolder = new ViewHolder();
			viewHolder.text = (TextView) convertView.findViewById(R.id.label);
			viewHolder.checkbox = (CheckBox) convertView.findViewById(R.id.check);
			
			viewHolder.text.setTag(shoeActionInmigrant);
			viewHolder.checkbox.setTag(shoeActionInmigrant);
			
			convertView.setTag(viewHolder);

			viewHolder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
						public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
							CheckBox cb = (CheckBox) buttonView;
							ShoeActionsInmigrant element = (ShoeActionsInmigrant) cb .getTag();
							element.setStatus(cb.isChecked());
							dataSource.updateActivity(new String[]{element.getIdActivity()}, (cb.isChecked()==true) ? new Integer(1) : new Integer(0), typeActionShoe.ACTIVITY.toString());
						}
					});
		} else {
			viewHolder = (ViewHolder) convertView.getTag();	 
		}
		
		viewHolder.text.setText(shoeActionInmigrant.toString());
		viewHolder.checkbox.setChecked(shoeActionInmigrant.isStatus());
		viewHolder.setIdElement(shoeActionInmigrant.getIdActivity());
		return convertView;
	}

}
